package com.mng.JdbcTemplateTest.dao;


import com.mng.JdbcTemplateTest.model.Department;
import com.mng.JdbcTemplateTest.model.Employee;
import com.mng.beanTest2.Emp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class EmployeeDao {
  @Autowired
  JdbcTemplate jdbcTemplate;
  //insert
  public void add(Employee employee){
    String sql = "insert into tbl_employee values (?,?,?,?,?)";
    Object[] args = {employee.getId(), employee.getLastName(),
        employee.getGender(), employee.getEmail(), employee.getDeptId()};
    int update = jdbcTemplate.update(sql,args);
    System.out.println(update);
  }
  //update
  public void updateEmployee(Employee employee){
    String sql = "update tbl_employee set email= ? where last_name = ? ";
    Object[] args = {employee.getEmail(),employee.getLastName()};
    int update  = jdbcTemplate.update(sql,args);
    System.out.println(update);
  }
  //delete
  public void deleteEmployee(Employee employee){
    String sql = "delete from tbl_employee where last_name = ? ";
    Object[] args = {employee.getLastName()};
    int update  = jdbcTemplate.update(sql,args);
    System.out.println(update);
  }
  //select 值
  public Integer countEmployee(Department department){
    String sql = "select count(*) from tbl_employee where dept_id = ?";
    Object[] args ={department.getId()};
    Integer count = jdbcTemplate.queryForObject(sql,Integer.class,args);
    return count;
  }
  //select 对象
  public Employee findEmployee(Long id){
    String sql = "select * from tbl_employee where id = ?";
    Employee employee = jdbcTemplate.queryForObject(sql,
        new BeanPropertyRowMapper<Employee>(Employee.class),id);
    return  employee;
  }
  //select 对象列表
  public List<Employee> findAllEmployee(Department department){
    String sql = "select * from tbl_employee where dept_id = ?";
    Object[] args  = {department.getId()};
    List<Employee> employeeList = jdbcTemplate.query(sql,
        new BeanPropertyRowMapper<Employee>(Employee.class),args);
    return employeeList;
  }
  //batch update
  public void batchAddEmployee(List<Employee> employeeList){
    String sql = "insert into tbl_employee values (?,?,?,?,?)";
    List<Object[]> argslist = new ArrayList<>();
    for(Employee employee:employeeList){
      argslist.add(new Object[]{employee.getId(), employee.getLastName(),
          employee.getGender(), employee.getEmail(), employee.getDeptId()});
    }
    int[] ints = jdbcTemplate.batchUpdate(sql, argslist);
    System.out.println(ints);
  }
}
